package org.fmi.lje.pp.impl;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.listener.Log4jListener;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Path;
import org.fmi.lje.model.UmlGenProject;
import org.fmi.lje.pp.ProjectCompiler;
import org.fmi.lje.pp.classpath.ClasspathResolver;

import com.google.inject.Inject;

public class AntProjectCompiler implements ProjectCompiler {

	private ClasspathResolver classpathResolver;

	@Inject
	public AntProjectCompiler(ClasspathResolver classpathResolver) {
		this.classpathResolver = classpathResolver;
	}

	public void compileProject(UmlGenProject project) {
		Project antProject = configureAntProject(project);
		Javac javac = configureJavac(project, antProject);

		javac.execute();
	}

	private Project configureAntProject(UmlGenProject project) {
		Project antProject = new Project();
		antProject.init();

		Log4jListener log4jListener = new Log4jListener();
		antProject.addBuildListener(log4jListener);

		antProject.setBasedir(project.getProjectFolder());
		antProject.setName(project.getProjectName());

		return antProject;
	}

	private Javac configureJavac(UmlGenProject project, Project antProject) {
		Javac javac = new Javac();
		javac.setProject(antProject);
		javac.setIncludeantruntime(false);

		Path srcDir = new Path(antProject);
		srcDir.setPath(project.getSourceFolder());

		Path classpath = new Path(antProject);
		List<URL> urls = classpathResolver.getClasspath(project);

		for (URL url : urls) {
			Path file = classpath.createPath();
			file.setLocation(new File(url.getFile()));
		}

		String projectFolder = project.getProjectFolder();
		File destDir = new File(projectFolder  + File.separator + "umlgen-output");
		if (!destDir.exists()) {
			destDir.mkdir();
		}

		javac.setDestdir(destDir);

		javac.setClasspath(classpath);
		javac.setSrcdir(srcDir);
		
		javac.setFork(true);
		
		return javac;
	}
}
